
package org.apache.solr.core;

import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.lucene40.Lucene40Codec;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaAware;
import org.apache.solr.schema.SchemaField;

/**
 * Per-field CodecFactory implementation, extends Lucene's
 * and returns postings format implementations according to the
 * schema configuration.
 *
 * @lucene.experimental
 */
public class SchemaCodecFactory extends CodecFactory implements SchemaAware {

    private Codec codec;
    // TODO: we need to change how solr does this?
    // rather than a string like "Pulsing" you need to be able to pass parameters
    // and everything to a field in the schema, e.g. we should provide factories for 
    // the Lucene's core formats (Memory, Pulsing, ...) and such.
    //
    // So I think a FieldType should return PostingsFormat, not a String.
    // how it constructs this from the XML... i don't care.

    @Override
    public void inform(final IndexSchema schema) {

        codec = new Lucene40Codec() {
            @Override
            public PostingsFormat getPostingsFormatForField(String field) {
                final SchemaField fieldOrNull = schema.getFieldOrNull(field);
                if(fieldOrNull == null) {
                    throw new IllegalArgumentException("no such field " + field);
                }
                String postingsFormatName = fieldOrNull.getType().getPostingsFormat();
                if(postingsFormatName != null) {
                    return PostingsFormat.forName(postingsFormatName);
                }
                return super.getPostingsFormatForField(field);
            }
        };
    }

    @Override
    public Codec getCodec() {
        assert codec != null : "inform must be called first";
        return codec;
    }
}
